<template>
  <div >
    <div class="table_div">
      <!-- 搜索 -->
      <el-form ref="formSearch" :model="params" :inline="true" size="small">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="params.name"
            clearable
            class="filter-item"
            placeholder="支持模糊查询"
          />
        </el-form-item>
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
        <el-button class="filter-item" size="mini" icon="el-icon-close" @click="resetSearchData">重 置</el-button>
      </el-form>
    </div>
    <div class="table_div">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="add">新 增</el-button>
    </div>
    <!--表单组件-->
    <eForm ref="form" :is-add="isAdd"/>
    <!--表格渲染-->
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            v-loading="loading"
            :data="data"
            border
            stripe
            highlight-current-row
            size="small"
            style="width: 100%;"
            @current-change="handleCurrentChange">
            <el-table-column prop="roleName" label="角色名称"/>
            <el-table-column prop="roleSign" label="角色标识"/>
            <el-table-column :show-overflow-tooltip="true" prop="remark" label="描述"/>
            <el-table-column prop="gmtCreate" label="创建日期"/>
            <el-table-column label="操作" width="130px" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"/>
                <el-popover
                  :ref="scope.row.roleId"
                  placement="top"
                  width="180">
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.roleId].doClose()">取消</el-button>
                    <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.roleId)">确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"/>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            :current-page="page + 1"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @size-change="sizeChange"
            @current-change="pageChange"/>
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveRoleMenu"
            >保存</el-button>
          </div>
          <div>
            <a>菜单分类系统</a>
            <el-select v-model="appId" placeholder="请选择菜单分类系统" class="search_width" @change="getMenus">
              <el-option
                v-for="item in appLists"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            :check-strictly="true"
            default-expand-all
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
/* eslint-disable */
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import {listAll } from '@/api/app'
import {getMenuByAppId} from '@/api/menu'
import {getMenuIdsByRoleId,saveMenuByRoleId} from '@/api/roleMenu'
import { del } from '@/api/role'
import eForm from './form'
import Config from '@/config'

export default {
  components: { eForm },
  mixins: [initData,initDict],
  created() {
    this.setHeight(250); //高度需要调整
    this.getAppList()
    this.$nextTick(() => {

      this.initPageData()
    })
  },
  data() {
    return {
      // 点击菜单保存的时候加载
      menuLoading: false,
      // 是否显示按钮
      showButton: false,
      appLists: [],
      appId:'',
      roleId:'',
      menus: [],
      menuIds: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      delLoading: false,
    }
  },
  methods: {
    beforeInit() {
      this.url = 'role/listPage';
      return true
    },
    handleCurrentChange(val) {
      if (val) {
        this.showButton = true;
        // 每次点击item时，清空之前所选的数据
        this.roleId=val.roleId;
        this.$refs.menu.setCheckedKeys([]);
        getMenuIdsByRoleId(val.roleId).then(res => {
          this.menuIds = res.data;
        });

      }
    },
    getMenus() {
      //获取系统应用对应的菜单
      this.menus = [];
      getMenuByAppId(this.appId).then(res => {
        if (res.code == Config.code_200) {
          this.menus = res.data;
        } else {
          this.$notify.error({title: '失败', message: res.msg})
        }
      })
    },
    getAppList() {
      listAll().then(res => {
        if (res.code == Config.code_200) {
          this.appLists = res.data
        } else {
          this.$notify.error({title: '失败', message: res.msg})
        }
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    add() {
      this.isAdd = true;
      const _this = this.$refs.form;
      _this.dialog = true;
    },
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.form = data
      _this.dialog = true
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        if (res.code == Config.code_200) {
          this.initPageData()
          this.$notify({title: '删除成功', type: 'success',})
        } else {
          this.$notify.error({title: '失败', message: res.msg})
        }
        this.delLoading = false
        this.$refs[id].doClose()
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.response.data.message)
      })
    },
    saveRoleMenu(){
// 得到半选的父节点数据，保存起来
      const menus = [];
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach(function(data, index) {
        menus.push(data);
      })
      if (!this.appId){
        this.$notify.error({title: '失败', message: "请选择系统应用"})
        return;
      }
      saveMenuByRoleId(this.roleId,menus).then(res => {
        if (res.code == Config.code_200) {
          this.$notify({title: '成功', type: 'success',})
        } else {
          this.$notify.error({title: '失败', message: res.msg})
        }
      })

    },
  }
}
</script>

<style scoped>
  .table_div {
    padding: 8px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    color: #303133;
    -webkit-transition: 0.3s;
    transition: 0.3s;
  }

</style >
